package com.zoweunion.mechanic.service.app.impl;

import com.zoweunion.mechanic.dao.app.SpeedyLoginDao;
import com.zoweunion.mechanic.model.WxUserInfo;
import com.zoweunion.mechanic.plugins.shiro.JWTUtil;
import com.zoweunion.mechanic.service.app.SpeedyLoginService;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.MyException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings("unchecked")
public class SpeedyLoginServicelmpl implements SpeedyLoginService {

    @Autowired
    private SpeedyLoginDao speedyLoginDao;

    @Override
    public Map<String,Object> userInfoWithOpenId (String open_id){

        Map<String,Object> userInfoMap = speedyLoginDao.selectUserInfoWithOpenId(open_id);

        if (userInfoMap == null) {

            userInfoMap = new HashMap<>();

            userInfoMap.put("flag",false);

            userInfoMap.put("open_id",open_id);

        } else {

            userInfoMap.put("Authorization", JWTUtil.sign(userInfoMap.get("user_account").toString(),userInfoMap.get("user_password").toString()));
            userInfoMap.put("flag",true);
        }

        return userInfoMap;
    }

    @Override
    public Map<String, Object> userInfoWithWxId(String openId, Integer type) throws MyException {
        if (StringUtils.isBlank(openId)) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "没有获取微信openid");
        }
        Map<String, Object> userInfoMap;
        if (WxUserInfo.TYPE_WX.equals(type)) {
            userInfoMap = speedyLoginDao.selectUserInfoWithOpenId(openId);
        } else if (WxUserInfo.TYPE_ALIPAY.equals(type)) {
            userInfoMap = speedyLoginDao.selectUserInfoWithAliUserId(openId);
        } else {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "不支持操作");
        }
        if (userInfoMap == null) {
            userInfoMap = new HashMap<>();
            userInfoMap.put("flag", false);
            userInfoMap.put("open_id", openId);
        } else {
            userInfoMap.put("Authorization", JWTUtil.signNotExpire(userInfoMap.get("user_account").toString(), userInfoMap.get("user_password").toString()));
            userInfoMap.put("flag", true);
        }
        return userInfoMap;
    }

    @Override
    public int updateOpenId (Map<String,Object> map) {

        return speedyLoginDao.updateOpenId(map);
    }
}
